chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    switch (request.type) {
        case 'quesApi':
            quesApi = true
            break
        case 'groupApi':
            groupApi = true
            break
        case 'wordApi':
            wordIFrame = true
            break
        case 'downloadComplete':
            wordApi = true
            break
        case 'excelDownload':
            break
        case 'analyzeApi':
            analyzeApi = true
            break
        case 'floatChange':
            floatT = +request.data
            break
        case 'baseChange':
            baseT = +request.data
            break
        default:
            break
    }
})

window.addEventListener("DOMContentLoaded", () => {
    const body = document.body
    const div = document.createElement("div")
    div.innerHTML = `
    <div class="zj-container">
    <div class="info">
        <p>等待就绪</p>
    </div>
    <div class="speed">
        <p>基础速度：<span id="base"></span>秒</p>
        <div class="control base">
            <span for="base"></span>
        </div>
    </div>
    <div class="speed">
        <p>浮动速度：<span id="float"></span>秒</p>
        <div class="control float">
            <span for="float"></span>
        </div>
    </div>
    <div class="flex">
        <label for="download">自动
            <input type="checkbox" id="download"  />
        </label>
        <label for="review">忽略复习章节
            <input type="checkbox" id="review" />
        </label>
    </div>
    <div class="flex">
        <label for="old">剔除旧题
        <input type="checkbox" id="old" />
        </label>
        <label for="year">年份
            <input type="number" id="year" max="2030" min="2000" />
        </label>
    </div>
    <hr />
    <div class="flex">
        <div class="btn join success">开始 (s)</div>
        <div class="btn stop danger">停止(Esc)</div>
    </div>
    <hr />
    <div class="btn post success">生成细目表(e)</div>
    <div class="btn restart warning">重新开始(r)</div>
    <div class="btn zip">打包文件(z)</div>
</div>`
    body.appendChild(div)
    // restart()

    setYear(document.querySelector('.zj-container #year'))
    addQues()
    stopWorker()

    modifyTitle()
    // openWord()
    openExcel()
    downloadExcelHandle()

    restartHandle()
    zipHandle()
    dragEvent()

    const downloadEl = document.querySelector('.zj-container #download')
    downloadEl?.addEventListener('change', () => {
        localStorage.setItem("autoDownload", downloadEl.checked)
    })
    const reviewEl = document.querySelector('.zj-container #review')
    reviewEl?.addEventListener('change', () => {
        localStorage.setItem("review", reviewEl.checked)
    })
    setTimeout(() => {
        downloadEl && (downloadEl.checked = localStorage.getItem("autoDownload") == "true")
        reviewEl && (reviewEl.checked = localStorage.getItem("review") == "true")
        setText('float', floatT)
        setText('base', baseT)
        clear()
    }, 100)

    document.querySelector('.base span').addEventListener('mousedown', mouseDown)
    document.querySelector('.float span').addEventListener('mousedown', mouseDown)
    window.addEventListener('mouseup', mouseUp)
    window.addEventListener('mousemove', mouseMove)

    baseT = +(localStorage.getItem('base') || 500)
    floatT = +(localStorage.getItem('float') || 500)
    document.querySelector('.base span').style.left = (baseT - baseRange.min) * 170 / (baseRange.max - baseRange.min) + 'px'
    document.querySelector('.float span').style.left = (floatT - floatRange.min) * 170 / (floatRange.max - floatRange.min) + 'px'
})
let stop = true, quesApi = false, fileTitle = '',
    groupApi = false, wordIFrame = false,
    wordApi = false, analyzeApi = false,
    isDragging = false, position = { x: 0, y: 0 },
    stopA = true
const SERVER = 'http://localhost:8800'
const baseRange = { min: 300, max: 5000 },
    floatRange = { min: 0, max: 5000 }
let baseT = localStorage.getItem('base') || 500, floatT = localStorage.getItem('float') || 500
let mouseX = 0, active = null

// 注册事件
function setYear (numberEl) {
    numberEl?.addEventListener('change', () => {
        localStorage.setItem('year', numberEl.value)
    })
    numberEl.value = localStorage.getItem('year') || '2015'
}
function addQues () {
    if (window.location.href == 'https://zujuan.xkw.com/zujuan/') return
    document.querySelector('.zj-container .join')?.addEventListener('click', () => {
        if (document.querySelector(".zj-container #download")?.checked) {
            autoJoin()
        } else {
            addQuesClickHandler()
        }
    })
    window.addEventListener('keyup', (e) => {
        if (e.key == 's') {
            document.querySelector('.zj-container .join')?.click()
        }
    })
}
function stopWorker () {
    if (window.location.href == 'https://zujuan.xkw.com/zujuan/') return
    document.querySelector('.zj-container .stop')?.addEventListener('click', () => {
        stop = true
        stopA = true
        info("停止加入试卷")
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        })
    })
    window.addEventListener('keyup', (e) => {
        if (e.key == 'Escape') {
            stop = true
            stopA = true
            info("停止加入试卷")
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            })
        }
    })
}
function downloadWordHandle () {
    if (window.location.href != 'https://zujuan.xkw.com/zujuan/') return
    document.querySelector('.zj-container .word')?.addEventListener('click', download)
    window.addEventListener('keyup', (e) => {
        if (e.key == 'w') {
            download()
        }
    })
}
function restartHandle () {
    if (window.location.href != 'https://zujuan.xkw.com/zujuan/') return
    document.querySelector('.zj-container .restart')?.addEventListener('click', restart)
    window.addEventListener('keyup', (e) => {
        if (e.key == 'r') {
            restart()
        }
    })
}
function zipHandle () {
    document.querySelector('.zj-container .zip')?.addEventListener('click', fileZip)
    window.addEventListener('keyup', (e) => {
        if (e.key == 'z') {
            fileZip()
        }
    })
}
function downloadExcelHandle () {
    if (window.location.href != 'https://zujuan.xkw.com/zujuan/') return
    document.querySelector('.zj-container .post')?.addEventListener('click', openExcel)
    window.addEventListener('keyup', (e) => {
        if (e.key == 'e') {
            openExcel()
        }
    })
}

// 清空组卷
async function clear () {
    if (window.location.href == 'https://zujuan.xkw.com/zujuan/') return
    const restart = localStorage.getItem('restart') || false
    if (restart) {
        let el = null
        let confirmEl = null
        while (!el) {
            el = document.querySelector(".newcart-list a.deleteall")
            await sleep(500)
        }
        await sleep(500)
        el.click()
        while (!confirmEl) {
            confirmEl = document.querySelector(".tk-dialog .confirm-btn")
            await sleep(500)
        }
        await sleep(500)
        confirmEl.click()
        await sleep(100)
        localStorage.removeItem('restart')
        await sleep(100)
        let menu = null
        document.querySelector(".tree-box").scrollTo({
            top: 50, behavior: "smooth"
        })
        while (!menu) {
            menu = document.querySelector(".tree-top-ul")
            await sleep(500)
        }
        quesApi = false
        if (document.querySelector('.zj-container #download').checked) {
            nextWorker()
        }
    }
}
// 插件提示消息
async function info (msg, err = false) {
    const el = document.querySelector('.zj-container .info')
    const p = document.createElement("p")
    p.innerText = msg
    err && (p.classList.add('err'))
    el?.appendChild(p)
    const beforEl = p.previousElementSibling
    beforEl.style.transform = 'translateY(-100%)'
    sleep(200).then(() => {
        beforEl.remove()
    })
    await sleep(1)
    p.style.transform = 'translateY(0)'
}
// 获取当前章节标题
function getTitle () {
    if (window.location.href == 'https://zujuan.xkw.com/zujuan/') {
        fileTitle = (localStorage.getItem('prefix') || '') + '-' + (localStorage.getItem('fileTitle') || '')
    } else {
        const subject = document.querySelector('.subject-menu__title').innerText
        const volumeEl = document.querySelectorAll('.title-name .title-box span')
        let vol = ''
        volumeEl.forEach((i, index) => {
            if (index) {
                vol += "-" + i.innerText
            } else {
                vol = i.innerText
            }
        })
        localStorage.setItem('prefix', subject + '-' + vol)
        const currentNode = document.querySelector(".tree-node--selected")
        if (currentNode) {
            fileTitle = currentNode.querySelector('a')?.innerText || ''
            if (!currentNode.parentElement.classList.contains("tree-top-ul")) {
                let parentLiEl = currentNode.parentElement?.parentElement
                while (!parentLiEl.parentElement.classList.contains("tree-top-ul")) {
                    fileTitle = (parentLiEl.querySelector('.tree-node-name')?.querySelector('a').innerText || '') + "-" + fileTitle
                    parentLiEl = parentLiEl.parentElement?.parentElement
                }
            }
            localStorage.setItem('fileTitle', fileTitle)
        }
    }
    // 替换特殊字符规则
    //   "<": "《",
    //   ">": "》",
    //   ":": "：",
    //   "\"": "'",
    //   "/": "_",
    //   "\\": "、",
    //   "|": "｜",
    //   "?": "？",
    //   "*": "＊"
    fileTitle = fileTitle.replaceAll("<", "《")
        .replaceAll(">", "》")
        .replaceAll(":", "：")
        .replaceAll("\"", "'")
        .replaceAll("/", "_")
        .replaceAll("\\", "、")
        .replaceAll("|", "｜")
        .replaceAll("?", "？")
        .replaceAll("*", "＊")
    return fileTitle
}
// 延时函数
function sleep (time) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(true)
        }, time || (baseT + Math.random() * floatT))
    })
}
// 进入组卷中心
function gotoGroup () {
    if (window.location.href == 'https://zujuan.xkw.com/zujuan/') return
    const el = document.querySelector('.newcart-list a.enter-center')
    el?.click()
}
// 组卷页修改标题
async function modifyTitle () {
    if (window.location.href != 'https://zujuan.xkw.com/zujuan/') return
    // 获取节点标题
    getTitle()
    while (!fileTitle || fileTitle == '-') {
        info("生成标题错误", true)
        fileTitle = window.prompt('请输入标题')
    }
    // await sleep(1000)
    document.querySelector('#pui_maintitle').innerText = fileTitle
    info('修改标题成功')
}
// 是否是旧题
function oldExclude (checkEl, numberEl, val) {
    if (!checkEl.checked) return true
    return +numberEl.value <= +val
}

// 操作函数
async function addQuesClickHandler (level = null) {
    if (!stop) return
    stop = false
    quesApi = false
    // if (!new RegExp(/[g]\d+/g).test(window.location.href.split('/').pop() || '')) {
    //     alert('请先选择一个年级')
    //     stop = true
    //     stopA = true
    //     return
    // }
    info('开始加入试卷')
    // 设置章节标题
    getTitle()
    await startWorker(false, level)
    stop = true
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    })
    info("停止加入试卷")
}
async function startWorker (mode = false, level) {
    if (mode) {
        info('等待题目加载')
        while (!quesApi) {
            await sleep(500)
            if (stop) return
        }
        sleep().then(() => {
            quesApi = false
        })
    }
    info('题目已加载')
    await sleep(600)

    let topicNode = []
    while (!topicNode.length) {
        if (stop) return
        topicNode = document.querySelectorAll('.tk-quest-item.quesroot')
        await sleep(500)
    }
    // 获取题目节点
    for (const topic of topicNode) {
        if (level !== null && (stop || !level?.count)) return
        window.scrollTo({
            top: topic.clientHeight + topic.offsetTop - window.innerHeight + 100,
            behavior: 'smooth'
        })
        await sleep(200)
        // 是否已使用
        let used = topic.querySelector('.exam-item__custom')?.hasAttribute('hidden')
        if (!used) {
            info('题目已被使用，跳过')
        }
        // 判断题目时间
        const timeEl = topic.querySelector('.ques-additional .addi-msg')
        let str = timeEl?.innerText || ''
        const match = str.match(/^[0-9]+/g)
        if (match && used) {
            str = match[0]
            switch (str.length) {
                case 1:
                    str = ("200" + str)
                    break
                case 2:
                    str = ("20" + str)
                    break
                case 3:
                    str = ("3" + str)
                default:
                    break
            }
            used = oldExclude(document.querySelector('.zj-container #old'), document.querySelector('.zj-container #year'), str)
            if (!used) {
                info('题目太老，跳过')
            }
        }
        if (used) {
            // 获取加入试卷的按钮
            const button = topic.querySelector('.exam-item__info .ctrl-box a.addques')
            button?.click()
            level && (level.count = level.count - 1)
            info('加入试卷成功')
            // 获取上限提示弹窗
            await sleep(200)
            if (stop) return
            const dialog = document.querySelector('dialog')
            if (dialog) {
                stop = true
                gotoGroup()
            }
            await sleep()
            if (stop) return
        }
    }
    window.scrollBy({
        top: 500,
        behavior: 'smooth'
    })
    // 获取分页节点
    const pagin = document.querySelector('.tk-pager')
    const nextEl = document.querySelector('.tk-pager a.next-page')
    if (!pagin?.hasAttribute('hidden')) {
        const currentEl = pagin?.querySelector('.page-num.active')
        if (!currentEl?.nextSibling.hasAttribute('hidden')) {
            (currentEl?.nextSibling).click()
        } else {
            return
        }
    } else {
        return
    }
    await startWorker(true, level)
}
// 打开word文件下载窗口
async function openWord () {
    if (window.location.href != 'https://zujuan.xkw.com/zujuan/') return
    groupApi = false, wordIFrame = false

    const iframeEl = window.document.querySelector('dialog iframe')
    if (iframeEl) {
        info("关闭下载窗口")
        iframeEl.contentWindow?.document.querySelector('.close-btn').click()
        await sleep(500)
    }

    await sleep(1000)
    // while (!groupApi) {
    //     await sleep(200)
    // }
    await modifyTitle()
    document.querySelector('a.download-btn').click()
    await sleep(600)
    while (!wordIFrame) {
        await sleep(500)
    }
    await sleep(500)
    groupApi = false
    downloadWord()
}
// 配置word下载参数
async function downloadWord () {
    const iframeEl = window.document.querySelector('dialog iframe')
    if (!iframeEl) {
        info('未打开下载窗口', true)
        return
    }
    let c0, // 解析内容1
        c1, // 解析内容2
        c2, // 解析内容3
        s, // 试题来源
        cl, // 清空试题
        m, // 公式格式
        p,
        t,
        input0,
        input1,
        input2
    info("等待页面加载")
    while (!(m && s && c1 && c2 && t && p && cl)) {
        try {
            const checkbox = iframeEl?.contentWindow?.document.querySelector('.tk-checkbox-group')
            input0 = checkbox?.querySelector('input#downParse')?.checked
            input1 = checkbox?.querySelector('input#downKnowledge')?.checked
            input2 = checkbox?.querySelector('input#downDifficulty')?.checked
            c0 = checkbox?.children[0]
            c1 = checkbox?.children[1]
            c2 = checkbox?.children[2]
            s = iframeEl?.contentWindow?.document.querySelector('.tk-radio.xyio-download-pop_ques-from_isShowOrigin-quesbody')
            m = iframeEl?.contentWindow?.document.querySelector('.formulas li[value="officemath"]')
            t = iframeEl?.contentWindow?.document.querySelector('input[name="paperTitle"]')
            p = iframeEl?.contentWindow?.document.querySelector('.answer-pos .ques-end')
            cl = iframeEl?.contentWindow?.document.querySelector('.xyio-download-pop_clear-bag_false')
        } catch (e) { }
        await sleep(100)
    }
    await sleep(500)
    t.value = getTitle()
    await sleep(300)
    p.click()
    if (!input0) {
        await sleep(300)
        c0?.click()
    }
    if (!input1) {
        await sleep(300)
        c1.click()
    }
    if (!input2) {
        await sleep(300)
        c2.click()
    }
    await sleep(300)
    s.click()
    await sleep(300)
    m.click()
    await sleep(300)
    cl.click()
    await sleep()
    if (document.querySelector('.zj-container #download').checked) {
        download()
    }
}
// 下载word文件
async function download () {
    const iframeEl = window.document.querySelector('dialog iframe')
    if (!iframeEl) {
        info('未打开下载窗口', true)
        return
    }
    let b = null
    // info("等待页面加载")
    while (!b) {
        try {
            b = iframeEl?.contentWindow?.document.querySelector('.btn-box #btnDownloadPaper')
        } catch (e) { }
        await sleep(100)
    }
    info('开始生成word文件')
    await sleep(800)
    b.click()
    // wordApi = true
    while (!wordApi) {
        await sleep(500)
    }
    info('word下载完毕')
    await sleep(200)
    wordApi = false
    wordIFrame = false
    // openExcel()
    await sleep(500)
    downloadExcel()
    await sleep(1000)
    info("完成一轮")
}
// 打开excel下载窗口, 复制试卷分析表
async function openExcel () {
    if (window.location.href != 'https://zujuan.xkw.com/zujuan/') return
    groupApi = false, analyzeApi = false

    await sleep(1000)
    while (!groupApi) {
        await sleep(200)
    }
    await modifyTitle()
    const iframeEl = window.document.querySelector('dialog iframe')
    if (iframeEl) {
        info("关闭下载窗口")
        iframeEl.contentWindow?.document.querySelector('.close-btn').click()
        await sleep(500)
    }
    document.querySelector('a#zujuanPaperAnalyze').click()
    info('打开试卷分析窗口')
    while (!analyzeApi) {
        await sleep(500)
    }
    await sleep(500)
    await copyTable()
    await sleep(500)
    await openWord()
    // downloadExcel()
    // await sleep(1000)
    // info("完成一轮")
}
async function copyTable () {
    let table
    const iframeEl = window.document.querySelector('dialog iframe')
    const tableEl = iframeEl?.contentWindow?.document.querySelector('.ife-modal .basic-analyze table')
    table = tableEl ? tableEl.outerHTML : ''
    const parser = new DOMParser()
    const doc = parser.parseFromString(table, 'text/html')
    const tables = doc.querySelector('table')
    while (tables.innerText == '') {
        sleep(500)
    }
    tables?.setAttribute('style', 'margin: 0px 0px 1.25rem; padding: 0px; width: 733px; box-sizing: border-box; border-width: 1px 0px 0px 1px; border-top-style: solid; border-left-style: solid; border-top-color: rgb(214, 234, 255); border-left-color: rgb(214, 234, 255); border-image: initial; border-bottom-style: initial; border-bottom-color: initial; border-right-style: initial; border-right-color: initial; border-spacing: 0px; font-size: 0.75rem; color: rgb(0, 0, 0); font-family: &quot;Microsoft YaHei&quot;, &quot;PingFang SC&quot;, Helvetica, Tahoma, Arial, sana-serif; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: center; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;')
    const tbody = doc.querySelectorAll('tbody')
    tbody.forEach(i => {
        i.setAttribute('style', 'margin: 0px; padding: 0px;')
        // @ts-ignore
        for (const tr of i.children) {
            tr.setAttribute('style', 'margin: 0px; padding: 0px; height: 2rem;')
            for (const td of tr.children) {
                if (td.getAttribute('class') === 'basic-td-4') {
                    td.setAttribute('style', 'margin: 0px; padding: 0px; box-sizing: border-box; border-right: 1px solid rgb(214, 234, 255); border-bottom: 1px solid rgb(214, 234, 255); text-align: center; width: 527.039px; word-break: break-all; white-space: normal;')
                } else if (td.getAttribute('colspan')) {
                    td.setAttribute('style', 'margin: 0px; padding: 0px 1.25rem; box-sizing: border-box; border-right: 1px solid rgb(214, 234, 255); border-bottom: 1px solid rgb(214, 234, 255); text-align: left;')
                } else {
                    td.setAttribute('style', 'margin: 0px; padding: 0px; box-sizing: border-box; border-right: 1px solid rgb(214, 234, 255); border-bottom: 1px solid rgb(214, 234, 255); text-align: center;')
                }
            }
        }
    })
    const thead = doc.querySelectorAll('thead')
    thead.forEach(i => {
        i.setAttribute('style', 'margin: 0px; padding: 0px; height: 2rem; text-align: center; background: rgb(239, 248, 255);')
        // @ts-ignore
        for (const tr of i.children) {
            tr.setAttribute('style', 'margin: 0px; padding: 0px; height: 2rem;')
            for (const td of tr.children) {
                if (td.getAttribute('class') === 'basic-td-4') {
                    td.setAttribute('style', 'margin: 0px; padding: 0px; box-sizing: border-box; border-right: 1px solid rgb(214, 234, 255); border-bottom: 1px solid rgb(214, 234, 255); text-align: center; width: 527.039px; word-break: break-all; white-space: normal;')
                } else if (td.getAttribute('colspan')) {
                    td.setAttribute('style', 'margin: 0px; padding: 0px 1.25rem; box-sizing: border-box; border-right: 1px solid rgb(214, 234, 255); border-bottom: 1px solid rgb(214, 234, 255); text-align: left;')
                } else {
                    td.setAttribute('style', 'margin: 0px; padding: 0px; box-sizing: border-box; border-right: 1px solid rgb(214, 234, 255); border-bottom: 1px solid rgb(214, 234, 255); text-align: center;')
                }
            }
        }
    })
    const serializer = new XMLSerializer()
    table = serializer.serializeToString(doc)
    await sleep(100)
    const type = 'text/html'
    const blob = new Blob([table], { type })
    const data = [new ClipboardItem({ [type]: blob })]

    navigator.clipboard.write(data).then(() => {
        console.log('success')
        info('复制表格内容成功')
    })
}
async function downloadExcel () {
    // await copyTable()
    // await sleep(500) \/,\*,  \<,\>,
    let fileTitle = getTitle().trim()
    const xhr = new XMLHttpRequest()
    xhr.open('GET', SERVER + '/excel?name=' + fileTitle)
    info('开始下载excel文档')
    await sleep(200)
    xhr.onload = async function () {
        if (xhr.status == 200) {
            const res = JSON.parse(xhr.responseText)
            if (res.message == "restart") {
                info("自动重启中...")
                await sleep(700)
                restart()
            } else {
                info("excel文档下载成功")
            }
        } else {
            info(JSON.parse(xhr.responseText).error || '下载excel文档失败', true)
        }
    }
    xhr.onerror = function () {
        info('下载excel文档失败', true)
    }
    xhr.send()
}

async function restart () {
    if (window.location.href != 'https://zujuan.xkw.com/zujuan/') return
    localStorage.setItem('restart', 'true')
    await sleep(300)
    chrome.runtime.sendMessage('restart')
    await sleep(200)
    window.close()
    // history.go(-1)
}
async function fileZip () {
    const fileTitle = getTitle()
    const xhr = new XMLHttpRequest()
    xhr.open('GET', SERVER + '/zip?name=' + fileTitle)
    info('开始打包文件')
    xhr.onload = function () {
        if (xhr.status == 200) {
            info('文件打包成功')
            console.log('success')
        } else {
            info('文件打包失败', true)
            console.log('error')
        }
    }
    xhr.onerror = function () {
        info('文件打包失败', true)
        console.log('error')
    }
    xhr.send()
}
function dragEvent () {
    const dragEl = document.querySelector(".zj-container .info")
    dragEl?.addEventListener("mousedown", (e) => {
        isDragging = true
        position = { x: e.offsetX, y: e.offsetY }
    })
    window.addEventListener("mousemove", (e) => {
        if (isDragging) {
            const contentEl = document.querySelector(".zj-container")
            if (!contentEl) return
            contentEl.style.left = `${e.clientX - position.x - 5}px`
            contentEl.style.top = `${e.clientY - position.y + contentEl.clientHeight / 2 - 10}px`
        }
    })
    window.addEventListener("mouseup", () => {
        isDragging = false
    })
}
function setText (id, value) {
    localStorage.setItem(id, value)
    document.querySelector('#' + id).innerText = Math.floor(value / 100) / 10
}
function mouseDown (e) {
    active = e.target
    mouseX = e.clientX - e.target.offsetLeft
}
function mouseMove (e) {
    if (active) {
        let x = e.clientX - mouseX
        x = Math.min(Math.max(0, x), 170)
        active.style.left = `${x}px`
        const type = active.getAttribute('for')
        if (type == 'base') {
            baseT = baseRange.min + (baseRange.max - baseRange.min) * x / 170
            setText(type, baseT)
        } else {
            floatT = floatRange.min + (floatRange.max - floatRange.min) * x / 170
            setText(type, floatT)
        }
    }
}
function mouseUp () {
    active = null
}

async function autoJoin () {
    if (!stopA) return
    stopA = false
    setCurrentMenu()
    const levels = {
        全部: { sum: 0, count: 100, el: document.querySelector('.type-group-item[data-filter-type="ques-diff"] a[data-id="0"]') },
        容易: { sum: 0, count: 17, el: document.querySelector('.type-group-item[data-filter-type="ques-diff"] a[data-id="1"]') },
        较易: { sum: 0, count: 17, el: document.querySelector('.type-group-item[data-filter-type="ques-diff"] a[data-id="2"]') },
        适中: { sum: 0, count: 34, el: document.querySelector('.type-group-item[data-filter-type="ques-diff"] a[data-id="3"]') },
        较难: { sum: 0, count: 16, el: document.querySelector('.type-group-item[data-filter-type="ques-diff"] a[data-id="4"]') },
        困难: { sum: 0, count: 16, el: document.querySelector('.type-group-item[data-filter-type="ques-diff"] a[data-id="5"]') },
    }
    await getLevels(levels.全部)
    if (stopA) return
    if (levels.全部.sum <= 120) {
        // levels.全部.el.click()
        await sleep()
        document.querySelector('.zj-container #old').checked = false
        await sleep()
        if (stopA) return
        await addQuesClickHandler(levels.全部)
    } else if (levels.全部.sum <= 140) {
        // levels.全部.el.click()
        await sleep()
        document.querySelector('.zj-container #old').checked = true
        await sleep()
        await addQuesClickHandler(levels.全部)
        if (stopA) return
        if (!levels.全部.count) {
            await sleep()
            document.querySelector('.zj-container #old').checked = false
            await sleep()
            if (stopA) return
            // levels.全部.el.click()
            await sleep()
            await addQuesClickHandler(levels.全部)
        }
    } else {
        if (stopA) return
        const keys = ['困难', '较难', '容易', '较易', '适中']
        for (let index = 0; index < 5; index++) {
            levels[keys[index]].el.click()
            await getLevels(levels[keys[index]])
            if (stopA) return
            await sleep(200)
            if (levels[keys[index]].sum) {
                await sleep()
                document.querySelector('.zj-container #old').checked = true
                await sleep()
                await addQuesClickHandler(levels[keys[index]])
                await sleep(200)
                if (stopA) return
            }
            if (levels[keys[index]].count && index < 4) {
                levels[keys[index + 1]].count += levels[keys[index]].count
            }
            if (stopA) return
        }
        if (stopA) return
        if (levels.适中.count) {
            document.querySelector('.zj-container #old').checked = false
            await sleep()
            levels.全部.el.click()
            await sleep()
            await addQuesClickHandler(levels.全部)
        }
        if (stopA) return
    }
    await sleep(500)
    if (stopA) return
    stopA = true
    gotoGroup()
}

async function getLevels (level) {
    quesApi = false
    await sleep(500)
    level.el.click()
    while (!quesApi) {
        await sleep(500)
    }
    level.sum = +(document.querySelector('.topic-ctrl-bar .count-box .ques-sum').innerText)
}
async function setCurrentMenu () {
    const query = document.querySelector("li.tree-node--selected")
    let current_id = query?.getAttribute("tree-id")
    if (!query.parentElement.classList.contains('tree-top-ul')) {
        let parentEl = query?.parentElement?.parentElement
        while (parentEl && !parentEl?.classList.contains('tree-top-ul')) {
            current_id = (parentEl.getAttribute("tree-id") || "") + "-" + current_id
            if (parentEl?.parentElement.classList.contains('tree-top-ul')) {
                break
            }
            parentEl = parentEl?.parentElement?.parentElement
        }
    }
    sessionStorage.setItem('current_id', current_id)
}

async function nextWorker () {
    const current_id = sessionStorage.getItem("current_id")
    if (current_id) {
        const treeId = current_id.split("-"), tree = {}
        let currentEl = document.querySelector('ul.tree-top-ul')
        if (treeId.length < 2) return

        let nextEl = false
        treeId.forEach((id, index) => {
            if (!index) {
                tree[index] = currentEl.querySelector(`li[tree-id="${id}"]`)
            } else {
                tree[index] = tree[index - 1].querySelector(`li[tree-id="${id}"]`)
            }
        })
        while (!nextEl) {
            nextEl = tree[treeId.length - 1].nextElementSibling
            treeId.pop()
        }
        if (nextEl?.classList.contains('tree-leaf')) {
        } else if (nextEl?.querySelector("li.tree-leaf")) {
            nextEl = nextEl.querySelector("li.tree-leaf")
        } else { return }
        nextEl.querySelector("a").click()
        while (!quesApi) {
            await sleep(500)
        }
        if (document.querySelector('.zj-container #review').checked && !nextEl.nextElementSibling && !nextEl.previousElementSibling.classList.contains('tree-leaf')) {
            setCurrentMenu()
            await sleep(500)
            nextWorker()
            return
        }
        await sleep(500)
        autoJoin()
    }
}
